package com.cryann.mqttserver.mqttProcess.mqttMsgHandler;

import com.cryann.mqttserver.exception.MqttException;
import com.cryann.mqttserver.modle.MqttMessageStore;
import com.cryann.mqttserver.modle.MqttSendMessage;
import com.google.common.collect.ImmutableSet;
import io.netty.handler.codec.mqtt.MqttMessage;
import io.netty.handler.codec.mqtt.MqttMessageIdVariableHeader;
import io.netty.handler.codec.mqtt.MqttMessageType;
import org.springframework.stereotype.Component;

import java.util.Set;

/**
 * @author cRyann
 * @date 2018/12/29 0029 09:02
 * @description: [MQTT-2.3.1-6]	PUBACK, PUBREC, PUBREL报文必须包含与最初发送的PUBLISH报文相同的报文标识符。
 */
@Component
public class MQTT_2$3$2_6 extends AbstractMqttHandler {
    @Override
    protected Set<MqttMessageType> handlerType() {
        return ImmutableSet.of(MqttMessageType.PUBACK,
                MqttMessageType.PUBREC,
                MqttMessageType.PUBREL);
    }

    @Override
    protected boolean checkMsg(MqttMessage message) {
        MqttMessageIdVariableHeader variableHeader = (MqttMessageIdVariableHeader) message.variableHeader();
        MqttMessageStore.instance().getMap().forEach((k, v) -> {
            if ( v.stream().map(MqttSendMessage::getMessageId).noneMatch(s -> s.equals(variableHeader.messageId())) ) {
                throw new MqttException(" [MQTT-2.3.1-6] PUBACK, PUBREC, PUBREL报文必须包含与最初发送的PUBLISH报文相同的报文标识符。");
            }
        });
        return true;
    }
}
